<?php
require_once(libraries_get_path('vendor') . '/autoload.php');

class EntityImportItem {
  private $structure;
  private $entity;

  public function __construct($structure) {
    $this->structure = $structure;
    $this->entity = new Infinity\Entity($structure['entity_type'], $structure['entity_default_values']);
  }

  private function fieldPlugin($field, $field_data, $values) {
    $type = $field_data['type'];
    
    $value = array();
    foreach($field_data['cols'] as $col_name) {
      $value []= $values[$col_name];
    }
    switch($type) {
      case 'value':
        if(isset($field_data['delimiter'])) {
          $_value = implode($field_data['delimiter'], $value);
        } else {
          $_value = implode(' ', $value);
        }
        if(Infinity\String::startsWith($field, 'field_') || $field == 'body') {
          $this->entity->fieldManager()->setValue($field, 'value', $_value);
        } else {
          $this->entity->{$field} = $_value;
        }
        break;
      case 'tid':
      case 'taxonomy_term':
        $this->entity->fieldManager()->setValue($field, 'tid', $value[0]);
        break;
      case 'image':
        if(Infinity\File::isExists($value[0])) {
          $this->entity->fieldManager()->setFile($field, $value[0]);
        }
        break;
      default:
        if(module_load_include('inc', 'entity_import', 'plugin/'.$type)) {
          $fn = 'entity_import_'.$type;
          $fn($this->entity, $field, $value, $field_data);
        }
    }
  }

  public function save($values) {
    foreach($this->structure['fields'] as $field_name => $field) {
      $this->fieldPlugin($field_name, $field, $values);
    }
    // delete data
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', $this->structure['entity_type'])
      ->propertyCondition('title', $this->entity->title)
      ->propertyCondition('uid', $this->entity->uid)
      ->addMetaData('account', user_load(1));
    $result = $query->execute();
    if (isset($result[$this->structure['entity_type']])) {
      $ids = array_keys($result[$this->structure['entity_type']]);
      entity_delete_multiple($this->structure['entity_type'], $ids);
    }
    // save
    $this->entity->save();
    return $this->entity->getID();
  }
}